package today.rocky.memory.controller.advice;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import today.rocky.memory.common.CommonResult;
import today.rocky.memory.common.ResultCode;
import today.rocky.memory.exception.BusinessException;

import java.io.IOException;

/**
 * @author Rocky
 * @version 1.0
 * @date 2020/5/22 14:06
 * @description controller异常处理类
 */
@RestControllerAdvice
public class ControllerAdviceHandler {

	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(value = Exception.class)
	public CommonResult exceptionHandler(Exception ex){
		if(ex instanceof BusinessException){
			return 	CommonResult.failed("请求有误，请稍后再试:"+ex.getMessage());
		}else if(ex instanceof MethodArgumentNotValidException){
			MethodArgumentNotValidException e = (MethodArgumentNotValidException)ex;
			return 	CommonResult.failed(ResultCode.VALIDATE_FAILED,"参数校验错误:"+e.getBindingResult().getFieldError().getDefaultMessage());
		}else if(ex instanceof IOException){
			return 	CommonResult.failed("文件上传失败，请稍后再试:"+ex.getMessage());
		}
		return CommonResult.failed();
	}
}
